#!/bin/sh

# Detect the device that's used for the root file system
DEVICE=`mount | grep " / " | awk '{print $1}' | sed s/[0-9]\$//`

FSTABDATA=`cat /etc/fstab | grep /data`
if [ "$FSTABDATA" == "" ]; then
 echo "No filesystem defined in /etc/fstab"
 fsck -t f2fs ${DEVICE}4
 if [ "$?" != "0" ]; then
  mkfs -t f2fs -f ${DEVICE}4
 fi
fi

DATA=`mount | grep data`
if [ "$DATA" == "" ]; then
 echo "/data not mounted, trying to mount it"

 if [ ! -d /data ]; then
  echo "/data does not exist, creating it"
  mkdir /data
 fi

 mount ${DEVICE}4 /data
 if [ "$?" != "0" ]; then
  echo "Could not mount /data, trying to create a new file system"
  exit 1
 fi

 echo "adding /data to fstab"
 cat /etc/fstab | grep -v ${DEVICE}p4 > /tmp/fstab
 echo "${DEVICE}4    /data    auto    defaults,nofail    0    2" >>/tmp/fstab
 mv /etc/fstab /etc/fstab.bak
 mv /tmp/fstab /etc/fstab

fi

if [ -d /library ]; then
 if [ ! -d /data/library ]; then
  mv /library /data
 else
  echo "/data/library already exists, will use this one"
  mv /library /library.bak
 fi
fi

ln -s /data/library /library

if [ ! -d /data/library/music/local ]; then
 mkdir -p /data/library/music/local
fi

echo "disabling systemd service, this is a one-time job"
systemctl disable activate-data-partition.service

